#include <stdlib.h>
#include <memory.h>
#include <stdio.h>

#include "LogicPool/LogicInterface.h"
//#include "LogicPool/LogicPool.h"


void LogicInterface::ListDevices()
{
    unsigned int i, k;
    const unsigned int chars = 'Z'-'A'+1;
    uint8_t * deviceTypes;

    // create a list of device types: capital chars from 'A' to 'Z'
    deviceTypes = (uint8_t *) malloc(chars);
    bzero(deviceTypes, chars);
    for (i = 0; i < chars; i++)
        deviceTypes[i] = i + 'A';

    // probe all device types in the deviceTypes list
    for (i = 0; i < strlen((char *)deviceTypes); i++) {
        uint8_t device = deviceTypes[i];

        // device numbers start at one
        for (k = 1; k < 255; k++) {
            uint8_t mux, ver;
            uint16_t muxver;

            // read mux at address zero
            SetAddress(device, k, 0);
            //mux = ReadByte();
            muxver = ReadWord();
            mux = muxver & 0xff;
            ver = muxver >> 8;

            // mux is 255 if there's no such device, 
            // assume proper ordering of device numbers
            if (mux == (uint8_t) 0xff)
                break;

            printf("Device type %c, #%i: mux = 0x%.2x, type = %s, ver = %x\n", 
                device, k, mux, DeviceName(device), ver);
        }
    }
}


char * LogicInterface::DeviceName(uint8_t device)
{
    switch(device) {
        case 'L': return "logic module";
        case 'Q': return "QDC";
        case 'T': return "digital IO";
        case 'I': return "indicator";
        case 'C' : return "counter";
        default: return "unknown";
    };
}


void LogicInterface::GetFirmwareVersion(uint8_t &major, uint8_t &minor)
{
    uint32_t id = GetID();
    major = (id >> 8) & 0xff;
    minor = id & 0xff;
}


uint16_t LogicInterface::GetConfiguration()
{
    uint32_t id = GetID();
    return id >> 16;
}


bool LogicInterface::ReadBool()
{
	uint8_t data = ReadByte();
//	return data == LogicPool::level_high;
	return data == 0xff;
}


void LogicInterface::WriteBool(bool data)
{
//	WriteByte(data ? LogicPool::level_high : LogicPool::level_low);
	WriteByte(data ? 0xff : 0x80);
}

